package com.wufun.overseas.tools.filetransfer;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.Log;

import com.wufun.overseas.models.event.ApCreateEvent;

import org.greenrobot.eventbus.EventBus;

/**
 * Author: hest
 * Date:  2016/5/3
 */
public class CreateApWifiThread implements Runnable {
    private static final String TAG = CreateApWifiThread.class.getSimpleName();
    private static final int AP_WIFI_CREATE_TIME_OUT = 15 * 1000;
    private Context mContext;
    ApWifiUtil mApWifiUtil;


    public CreateApWifiThread(Context context) {
        this.mContext = context;
        mApWifiUtil = ApWifiUtil.getInstance(mContext);
    }

    @Override
    public void run() {
        mDownTimer.start();
    }


    //监听wifi 热点的计时器
    CountDownTimer mDownTimer = new CountDownTimer(AP_WIFI_CREATE_TIME_OUT, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            Log.d(TAG, "onTick: 开始倒计时"+millisUntilFinished/1000);
            if (millisUntilFinished / 1000 > 0) {
                checkApCreateSuccess();
            }
        }

        @Override
        public void onFinish() {
            apCreateFailed();
        }
    };


    //检查热点是否创建成功
    void checkApCreateSuccess() {
        if (mApWifiUtil.isWifiApEnabled()) {
            Log.d(TAG, "checkApCreateSuccess: ");
            ApCreateEvent event = new ApCreateEvent();
            event.status = ApCreateEvent.SUCCESS;
            EventBus.getDefault().post(event);
            mDownTimer.cancel();
        }
    }

    public void cancelDownTimer(){
        if(mDownTimer!=null){
            mDownTimer.cancel();
        }
    }

    void apCreateFailed() {
        ApCreateEvent event = new ApCreateEvent();
        event.status = ApCreateEvent.FAILED;
        EventBus.getDefault().post(event);
    }

}
